package mdm.com.web.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import mdm.com.util.BeanId;
import mdm.com.util.MD5;
import mdm.com.web.common.AjaxResponse;
import mdm.com.web.common.BaseController;
import mdm.com.web.common.Constant;
import mdm.com.web.entity.Permission;
import mdm.com.web.entity.User;
import mdm.com.web.entity.Wuser;
import mdm.com.web.service.UserService;
import mdm.com.web.session.TokenSession;
import mdm.com.web.session.TokenSessionManager;

import java.util.HashSet;
import java.util.List;
import java.util.Set;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

@Controller
@RequestMapping(value = "login")
@Api(description = "登录模块")
public class LoginController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoggerFactory.class);

    @Autowired
    private UserService userService;

    @ApiOperation(value = "WEB用户登录", notes = "请求参数:<br>" + "username 用户名<br>" + "password 密码")
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResponse doLogin(@RequestBody Wuser wuser) {
        // 生成token，创建会话
        try {
            LOGGER.info("begin to login,request info =" + wuser);
            Wuser user = userService.selectByUsernameAndPassword(wuser.getUsername(),
                    MD5.getStandardMd5(wuser.getPassword()));
            if (user == null) {
                return AjaxResponse.reponseBody(1, "用户名或密码错误", null);
            }
            UsernamePasswordToken token = new UsernamePasswordToken(wuser.getUsername(),
                    MD5.getStandardMd5(wuser.getPassword()),"web");
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            TokenSession session = new TokenSession();
            session.setAccountId(user.getId());
            session.setAccountName(user.getUsername());
            session.setCreateTime(System.currentTimeMillis());
            session.setLatestActiveTime(System.currentTimeMillis());
            String sessionToken = BeanId.generateUUId();
            // sessionKey
            session.setToken(sessionToken);
            TokenSessionManager.getInstance().addDomainTokenSession(session);
            Set<String> functionPermissionTokens = new HashSet<>();
            functionPermissionTokens.add("user_management");
            functionPermissionTokens.add("root_management");
            JSONObject result = new JSONObject();
            result.put("token", sessionToken);
            result.put("permissionTokens", functionPermissionTokens);
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }
    
    @ApiOperation(value = "用户登录-APP", notes = "请求参数:<br>" +
            "username 用户名<br>" +
            "password 密码"+
            "environment 环境"+
            "language 语言")
    @ResponseBody
    @RequestMapping(value = "/applogin", method = RequestMethod.POST)
    public AjaxResponse appLogin(@RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("environment") String environment,
            @RequestParam("language") String language) {
        
        LOGGER.info("==app login==");
        LOGGER.info("username={"+username+"},password={+"+password+"},environment={"+environment+"},language={"+language+"}");
//        HttpServletRequest req = HttpContextUtils.getHttpServletRequest();
//        System.out.println("====header===language====="+req.getHeader("language"));
//        System.out.println("====header===env====="+req.getHeader("env"));
        try {
            User accountInfo = userService.selectDetailByUsername(username);
            if(accountInfo == null) {
                return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
            }
            UsernamePasswordToken token = new UsernamePasswordToken(username, MD5.getStandardMd5(password),"app");
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);

            TokenSession session = new TokenSession();
            
            session.setAccountId(accountInfo.getcUserId());
            session.setAccountName(accountInfo.getcUsername());
            session.setNickName(accountInfo.getcNickname());
            session.setCreateTime(System.currentTimeMillis());
            session.setLatestActiveTime(System.currentTimeMillis());
            
            session.setUserType(accountInfo.getUser_type());
            session.setEnvironment(environment);
            session.setLanguage(language);

            JSONArray functionPermissions = new JSONArray();
            Set<String> functionPermissionTokens = new HashSet<>();
            List<Permission> permissions = accountInfo.getcPermissions();
            for (Permission permission : permissions) {
                functionPermissionTokens.add(permission.getcPermissionType());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("permissionName", permission.getcPermissionName());
                jsonObject.put("permissionToken", permission.getcPermissionType());
                jsonObject.put("permissionDetailToken", permission.getSubDetail());
                functionPermissions.add(jsonObject);
            }
            session.setFunctionPermissionTokens(functionPermissionTokens);
            session.setFunctionPermission(functionPermissions);
            
            // 生成token，创建会话
            String sessionToken = BeanId.generateUUId();
            // sessionKey
            session.setToken(sessionToken);
            TokenSessionManager.getInstance().addDomainTokenSession(session);
            JSONObject result = new JSONObject();
            result.put("token", sessionToken);
            result.put("permissionTokens", functionPermissionTokens);
            result.put("permissionDetails", functionPermissions);
            result.put("userType", accountInfo.getUser_type());
            result.put("zbukrs", accountInfo.getZbukrs());
            return AjaxResponse.reponseBody(Constant.SUCCESS_CODE, Constant.SUCCESS_MSG, result);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResponse.reponseBody(Constant.FAIL_CODE, Constant.FAIL_MSG, null);
        }
    }

}
